import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { exec } from 'child_process'
import path from 'path'
import fs from 'fs'
const inputMethodManager = require('./inputMethodManager')

inputMethodManager
  .getCurrentInputMethod()
  .then((imId) => {
    console.log('当前输入法ID:', imId)
  })
  .catch((err) => {
    console.error('查询失败:', err)
  })
// import robot from 'robotjs'

const logFile = path.join(app.getPath('userData'), 'main-process.log')

function log(message) {
  const timeStamp = new Date().toLocaleString()
  const time = new Date().toLocaleTimeString()
  const logMessage = `${timeStamp} ${time}: ${message}\n`

  console.log(message)
  fs.appendFileSync(logFile, logMessage)
}

function showWindowOSK() {
  const oskPath = path.join('C:\\Windows', 'System32', 'osk.exe')
  log(`尝试显示键盘 ${oskPath}`)

  try {
    exec('start "" "C:\\Windows\\System32\\osk.exe"', (error) => {
      if (error) {
        log(`打开屏幕键盘出错：${error}`)
      } else {
        log('打开屏幕键盘成功')
      }
    })
  } catch (error) {
    log(`启动键盘进程出错：${error}`)
  }
}
function hideWindowOSK() {
  log('尝试关闭键盘')
  const command =
    "powershell.exe -Command \"Start-Process -FilePath 'taskkill' -ArgumentList '/F', '/IM', osk.exe', '/T', -Verb RunAs -WindowStyle hidden\""
  exec(command, (error, stdout, stderr) => {
    if (error) {
      log(`关闭屏幕键盘出错：${error}`)
      exec('taskkill /IM osk.exe', (err) => {
        if (err) {
          log(`备用方法关闭屏幕键盘也失败：${err}`)
        } else {
          log('使用备用方法成功关闭键盘')
        }
      })
    } else {
      log('关闭屏幕键盘成功')
    }
    if (stderr) {
      log(`关闭键盘stderr输出： ${stderr}`)
    }
  })
}

function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(async () => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  ipcMain.on('show-keyboard', () => {
    showWindowOSK()
  })

  ipcMain.on('hide-keyboard', () => {
    hideWindowOSK()
  })
  ipcMain.on('toggle-input-method', () => {
    log('切换输入法')
    // robot.keyTap('ctrl', 'space')
    // exec('osk')
  })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  try {
    const allIme = await inputMethodManager.getAllInputMethods()
    console.log('系统中所有输入法：', allIme)

    // 可将结果存储起来，供后续切换使用
    // 例如：保存常用输入法ID
    const englishIme = allIme.find(
      (ime) => ime.name.includes('英文') || ime.name.includes('English')
    )
    const chineseIme = allIme.find(
      (ime) => ime.name.includes('中文') || ime.name.includes('Chinese')
    )

    if (englishIme) console.log('英文输入法ID：', englishIme.id)
    if (chineseIme) console.log('中文输入法ID：', chineseIme.id)
  } catch (err) {
    console.error('获取输入法列表失败：', err)
  }
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// function exec(arg0: string, arg1: (error: any) => void) {
//   throw new Error('Function not implemented.')
// }
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
